package com.wowangz.cms.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import com.wowangz.cms.syscore.SqlSessionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.UserContext;
import com.wowangz.cms.user.api.LoginController;
import com.wowangz.cms.user.api.ResetPassController;

/**
 * 自定义拦截器
 * @author 
 * @date 
 */
public class IssInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 最后执行，可用于释放资源
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//关闭当前线程中的连接
		if(handler instanceof BaseController)
		{
			SqlSessionContainer sqlSessionContainer = new SqlSessionContainer();
			sqlSessionContainer.closeSqlSession();
		}
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 显示视图前执行
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception
	{

		super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * Controller之前执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		
		UserContext userContext = (UserContext)WebUtils.getSessionAttribute(request, "userContext");
		
		if(handler instanceof LoginController)
		{
			userContext = new UserContext();
		}
		if (handler instanceof ResetPassController) {
			return true;
		}		
		
		//如果是访问的controller层
		if(handler instanceof BaseController)
		{
			
			HttpSession session = request.getSession();
			//得到总公司ID
			Long orgId = (Long)session.getAttribute("orgId");
			
			//orgId作为条件 通过redis集群路由表查找本地redis服务器
			//通过sessionId 在本地redis服务器中查找相应的登录信息
			
			if(userContext== null)
			{
				response.sendRedirect(request.getContextPath() + "/sessionOut.jsp");
				return false;
			}
			BaseController baseController = (BaseController)handler;
			baseController.setUserContext(userContext);
		}
		
		String url = request.getRequestURI();
		
		return super.preHandle(request, response, handler);
	}
}